﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace EDIConsole
{
	public abstract class ILogger
	{
		abstract public void ClearLogs();
		abstract public void WriteLogs(string logText);
	}

	public class Logger : ILogger
	{
		/// <summary>
		/// имя файла лога
		/// </summary>
		string LogFileName;

		/// <summary>
		/// Логгер
		/// </summary>
		EventLog eventLog;

		#region ClearLogs() -- Очистить лог файл 
		public override void ClearLogs()
		{
			if (!File.Exists(LogFileName))
			{
				// Create a file to write to.
				using (StreamWriter sw = File.CreateText(LogFileName))
				{
					sw.WriteLine("Создан новый лог " + DateTime.Now.ToString());
				}
			}
		}
		#endregion ClearLogs

		#region WriteLogs(string logText) -- Записать в лог
		public override void WriteLogs(string logText)
		{
			// This text is always added, making the file longer over time
			// if it is not deleted.
			using (StreamWriter sw = File.AppendText(LogFileName))
			{
				sw.WriteLine(logText);
			}
			Console.WriteLine(logText);
			AddLog(logText);
		}
		#endregion WriteLogs

		#region AddLog
		/// <summary>
		/// 
		/// </summary>
		public void AddLog(string log)
		{
			try
			{
				if (!EventLog.SourceExists("EDIService"))
				{
					EventLog.CreateEventSource("EDIService", "EDI");
				}
				eventLog.Source = "EDIService";
				eventLog.WriteEntry(log);
			}
			catch { }
		}
		#endregion AddLog

		#region Logger(string logFileName) -- Конструктор
		public Logger(string logFileName = "EDIConsole.log")
		{
			LogFileName = logFileName;

			eventLog = new EventLog("EDI");
		}
		#endregion Logger
	}
}
